<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./node_modules/tracking/build/tracking-min.js"></script>
  <script src="./face.js"></script>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    #config {
      position: fixed;
      display: flex;
      align-items: center;
      justify-content: space-around;
      bottom: 0;
      left: 0;
      background-color: #000;
      width: 100%;
      height: 20%;
    }

    img {
      object-fit: cover;
      /* object-fit: contain; */
      /* object-fit: scale-down; */
      border-radius: 100%;
    }

    #img {
      border: 1px solid #fff;
    }

    video, canvas {
    position: absolute;
  }


  </style>
</head>

<body>
  <video id="video" style="width: 100%;height: 80vh;"></video>
  <canvas id="imgphone" src="" style="width: 100%;height: 80vh;" alt=""></canvas>
  <div id="config">
    <img src="./大号选中背景.png" id="img" style="height:70px;width:70px" alt="" />
    <!-- <div id="btn">获取摄像头</div> -->
    <div id="btn2">
      <img src="./单选按钮-选中.png" style="height: 70px;width: 70px;" alt="">
    </div>
    <div id="btn3">
      <img src="./重置.png" style="height: 70px;width: 70px;" alt="">
    </div>
    <!-- <div id="btn">获取摄像头</button>
    <div id="btn1">关闭摄像头</button>
    <div id="btn2">拍摄</button> -->
  </div>
  <div id="content" >

  </div>
</body>

</html>
<script>
  var friends = ['Thomas Middleditch', 'Martin Starr', 'Zach Woods'];

  let video = document.querySelector("video")
  let canvas = document.querySelector("#imgphone")
  var ctx = canvas.getContext("2d");
  let btn3 = document.querySelector("#btn3")//调整摄像头
  let image = document.querySelector("#img")//预览
  let btn2 = document.querySelector("#btn2")
  let mediaStreamTrack = null;//媒体流变量
  let front = true;//摄像头前设置
    // 判断是否拍照
    let flag = 0
    let tipFlag = 0
 // 新建一个tracker实例
 const tracker = new tracking.ObjectTracker(['face']); // 可选 face, eye, mouth, 需要引入相应的js
    
    // 设置步长
    tracker.setInitialScale(4);
      tracker.setStepSize(1.7);
      tracker.setEdgesDensity(0.1);
    
    // 绑定监听方法
    tracker.on('track', handleTracked);
    function handleTracked(event) {
      if (event.data.length === 0) {
        // 没有检测到
        console.log('');
        // alert("没有检测到人脸")
      } else {
        // 提示用户已经检测到人脸
        if(!tipFlag) {
        //  alert("检测人脸成功，正在拍照，请保持不动2秒！")
        }
        
        // 1秒后拍照，仅拍一次
        if(!flag) {
          flag = 1;
          setTimeout(() => {
            // 模拟btn点击事件
            btn2.click();
            alert("拍照完成！")
            tipFlag = 1
          }, 1000);
        }
        // 人脸数据点阵处理
        // event.data.forEach(window.plot)
        // document.querySelector("#content").innerHTML = JSON.stringify(event.data)
        event.data.forEach(function(rect) {
          ctx.clearRect(0,0,canvas.width, canvas.height);
          ctx.strokeStyle = '#c48';
          ctx.strokeRect(rect.x+25, rect.y, rect.width+50, rect.height+100);
          ctx.font = '11px Helvetica';
          ctx.fillStyle = "#c48";
          ctx.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
          ctx.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
          });
      }
    }
    // 开始追踪
    tracking.track('#video', tracker);
   
  function init() {
    var constraints = {
      video: {
        // width: { min: 1024, ideal: 1280, max: 1920 },
        // height: { min: 576, ideal: 720, max: 1080 },
        facingMode: (front ? "user" : "environment")
      },
      Audio: false
    };
    window.tracking.initUserMedia_(video)
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      /**
       * facingMode 媒体类型 environment 后置摄像头 user前置摄像头
       * 
       * video 这里做兼容处理 对于相机的分辨率做出最好的优化选择
       * */
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        mediaStreamTrack = stream.getTracks()[0];
        try {
          video.srcObject = stream;
        } catch (error) {
          video.src = window.URL.createObjectURL(stream);
        }
        video.onloadedmetadata = function (e) {
          video.play();
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
        };
      }).catch(function (err) {
        console.log(err);
      })
    }
  }
  //监听拍照
  btn2.addEventListener('click', () => {
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    ctx.drawImage(video, 0, 0,
      video.videoWidth
      , video.videoHeight);
    image.src = canvas.toDataURL("image/png");
  })
  init()
  btn3.addEventListener('click', () => {
    front = !front
    mediaStreamTrack.stop()
    init()
  })

  //监听关闭摄像头
  // document.querySelector("#btn1").addEventListener('click', () => {
  //  
  // })

</script>